#include "widgetflip.h"
#include <QResizeEvent>
#include <QApplication>

#include <QDebug>

WidgetFlip::WidgetFlip(QWidget *front, QWidget *back, QWidget *parent) : QWidget(parent)
{
    m_front = front;
    m_back = back;
    front->setParent(this);
    back->setParent(this);
    back->hide();
    flipped = false;

    setFocusPolicy(Qt::ClickFocus);
    m_switchButton = new QToolButton(this);
    m_switchButton->setIconSize(QSize(16, 16));
    m_switchButton->setFocusPolicy(Qt::NoFocus);
    m_switchButton->setIcon(QIcon(":/images/edit-256.png"));
    connect(m_switchButton, SIGNAL(clicked()),
            this, SLOT(flip()));
}

QSize WidgetFlip::sizeHint() const
{
    return m_front->sizeHint();
}

QWidget *WidgetFlip::front() const
{
    return m_front;
}

QWidget *WidgetFlip::back() const
{
    return m_back;
}

void WidgetFlip::mouseDoubleClickEvent(QMouseEvent *e)
{
    if (!flipped)
        flip();

    QWidget::mouseDoubleClickEvent(e);
}

void WidgetFlip::resizeEvent(QResizeEvent *e)
{
    QSize bsize = m_switchButton->size();
    int x = e->size().width() - bsize.width();

    m_switchButton->move(x, 0);

    QWidget::resizeEvent(e);
}

void WidgetFlip::focusOutEvent(QFocusEvent *e)
{
//    qDebug() << "focus out";
//    if (QApplication::focusWidget() == m_back)
//        return;
//    qDebug() << "flip";
//    flip();
//    QWidget *t = qobject_cast<QWidget *>(e);
//    if(t)
//        qDebug() << "Success";
//    else qDebug() << "zero";
//    flipped = true;
//
    QWidget::focusOutEvent(e);
}

void WidgetFlip::flip()
{
    if (flipped) { // front
        m_front->show();
        m_back->hide();
        m_switchButton->setIcon(QIcon(":/images/edit-256.png"));
        //m_switchButton->show();
        flipped = false;
    } else { // back
        m_back->show();
        m_front->hide();
        m_switchButton->setIcon(QIcon(":/images/ok.png"));
        //m_switchButton->hide();
        flipped = true;
    }
}
